package projectiles;

import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.ImageIcon;

import core.Model;
import core.ShootingUnit;
import core.Vector;
import enemies.Enemy;

public class Nuke extends Projectile {
	
	private static final ImageIcon image = new ImageIcon("images/nuke.gif");
	private static final int damage = 300;
	private static final int speed = 900;
	
	private Enemy des; //enemy object.

	public Nuke( ShootingUnit origin, Point2D.Double position, int viewAngle, Enemy destn ) {
		super(origin, position, viewAngle, new Dimension(Nuke.image.getIconWidth(), Nuke.image.getIconHeight()), Nuke.image, Nuke.damage, destn.getPosition(), Nuke.speed );
		this.des = destn;
	}
	
	public boolean update()
	{	
		//missile aanpassen
		//controleren of enemy nog health heeft
		if(des.getHealth() > 0){
			//de vector richting updaten.
			super.direction = new Vector( des.getPosition().x - super.position.x, des.getPosition().y - super.position.y ).normalize();
		calcViewAngle();
		}else{
			//nieuwe enemy zoeken
			
		}
		
		//superklasse aanroepen
		super.update();
		return true;
	}
	
	private void calcViewAngle(){
		// Viewangle aanpassen, moet wijzen naar enemy
		
		Point2D.Double enemyPos = des.getPosition();
		double x = enemyPos.getX()-position.x;
		double y = enemyPos.getY()-position.y;
		//vijand links van toren
		if( x < 0 ){
			//vijand hoger dan toren
			x *= -1;
			if( y < 0 ){
				y *= -1;
				super.viewAngle = (int)Math.toDegrees( (Math.atan( ( y/x )   )) ) + 90 ;
			}
			//vijand lager dan toren
			else if( y > 0 ){
				super.viewAngle = (int)Math.toDegrees( (Math.atan( ( x/y )   )) );
			}
		//vijand rechts van toren
		} else if( x >= 0 ){
			if( y < 0 ){
				y *= -1;
				super.viewAngle = (int)Math.toDegrees( (Math.atan( ( x/y )   )  ) )+ 180;
			} else if( y > 0 ){
				super.viewAngle = (int)Math.toDegrees( (Math.atan( ( y/x  )   ))   )+ 270;
			}
		}
	
	}
	
	public void setEnemy(Enemy e){
		this.des = e;
	}
	
	public Enemy getEnemy(){
		return des;
	}
	
	public boolean calcEnemyForNuke( ArrayList<Enemy> enemies ){
		Collections.shuffle( enemies );
		
		// Random toewijzen
		Enemy enemy = null;
		
		for( Enemy x : enemies ){
			if ( !x.isOutsideView() && x.getHealth() > 0 )
				enemy = x;
		}
		
		if ( enemy == null )
			return false;
		else
		{
			if( enemy.getBounds().intersects(0, 0, Model.battlefieldWidth,  Model.battlefieldHeight )){
				this.setEnemy( enemy );
				return true;
			} else {
				return this.calcEnemyForNuke( enemies );
			}
		}
	}

}
